package org.qiyu.live.im.core.server.handler.impl;

import com.alibaba.fastjson.JSON;
import io.netty.channel.ChannelHandlerContext;
import jakarta.annotation.Resource;
import org.qiyu.live.im.core.server.common.ImContextUtils;
import org.qiyu.live.im.core.server.common.ImMsg;
import org.qiyu.live.im.core.server.service.MsgAckServiceHandler;
import org.qiyu.live.im.core.server.handler.SimpleHandler;
import org.qiyu.live.im.dto.ImMsgBody;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * Created with IntelliJ IDEA.
 * Description: ackHandler 主要接收客户端的ack,如果接收到客户端的ack就将ack记录删除
 * User: sfx
 * Date: 2023-10-07
 * Time: 16:48
 */
@Component
public class ACKMsgHandler implements SimpleHandler {

    private final Logger logger = LoggerFactory.getLogger(ACKMsgHandler.class);

    @Resource
    private MsgAckServiceHandler msgAckServiceHandler;

    @Override
    public void handler(ChannelHandlerContext ctx, ImMsg msg) {
        // 1. 对消息包进行校验
        // 1.1 对userId, appId 进行校验
        Long userId = ImContextUtils.getUserId(ctx);
        Integer appId = ImContextUtils.getAppId(ctx);
        if (userId == null || appId == null || userId < 10000 || appId < 10000) {
            logger.error("attr error msg={}", msg);
            ctx.close();
            throw new IllegalArgumentException("attr error");
        }
        // 2. 对body进行校验
        byte[] body = msg.getBody();
        if (body == null || body.length == 0) {
            ctx.close();
            logger.error("body error msg={}", msg);
            throw new IllegalArgumentException("body error");
        }
        // 2. 如果接收到了客户端的ack,我就将消息删除.
        msgAckServiceHandler.doMsgAck(JSON.parseObject(body, ImMsgBody.class));
    }
}